package com.lottery.ruok.lottrey.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.AptitudeLotteryActivity;
import com.lottery.ruok.lottrey.activity.BetListActivity;
import com.lottery.ruok.lottrey.adapter.AptitudeAdapter;
import com.lottery.ruok.lottrey.eventbusObject.AddBetSuccess;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.CreateOrderRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.IssueNoListRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.CreateOrderResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.IssueNoListResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import utils.Utils;

import static com.lottery.ruok.lottrey.activity.BetListActivity.results;

public class AptitudeFragment extends BaseFragment {
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.no_num)
    EditText noNum;
    @BindView(R.id.multiple)
    EditText multiple;
    @BindView(R.id.interval)
    EditText interval;
    @BindView(R.id.interval_multiple)
    EditText intervalMultiple;
    @BindView(R.id.advance)
    LinearLayout advance;
    @BindView(R.id.confirm)
    TextView confirm;
    private ArrayList<IssueNoListResponse> issueNoListResponses;

    private AptitudeAdapter aptitudeAdapter;

    private AptitudeLotteryActivity aptitudeLotteryActivity;

    private int multipleNumber = 1;
    private int intervalNumber = 2;
    private int intervalMultipleNumber = 2;

    public int wholeNum;
    public String wholeData;

    public void setResults(int num, String data) {
        wholeNum = num;
        wholeData = data;
        if((getArguments().getBoolean("isAdvanced") && aptitudeLotteryActivity.nowFocus == 1) || (!getArguments().getBoolean("isAdvanced") && aptitudeLotteryActivity.nowFocus == 0)){
            aptitudeLotteryActivity.result.setText(num + "期" + data + "元");
        }
    }

    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);

        if (context instanceof AptitudeLotteryActivity) {
            aptitudeLotteryActivity = (AptitudeLotteryActivity) context;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_aptitude, null);

        ButterKnife.bind(this, view);

        init();

        return view;
    }

    public void refreshList(){
        getList();
    }

    private void init() {
        noNum.setSelection(noNum.getText().length());

        if (getArguments().getBoolean("isAdvanced")) {
            advance.setVisibility(View.VISIBLE);

            interval.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if(interval.getText().toString().equals("")){
                        intervalNumber = 0;
                    } else {
                        intervalNumber = Integer.parseInt(interval.getText().toString());
                    }

                    //如果值是0或者不填的话，那么就是所有的倍数都是起始倍数；
                    setResults();
                }
            });

            intervalMultiple.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if(intervalMultiple.getText().toString().equals("")){
                        intervalMultipleNumber = 0;
                    } else {
                        intervalMultipleNumber = Integer.parseInt(intervalMultiple.getText().toString());
                    }

                    setResults();
                }
            });
        } else {
            advance.setVisibility(View.GONE);
        }

        getList();

        noNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(aptitudeAdapter != null) {
                    if (noNum.getText().toString().equals("") || Integer.parseInt(noNum.getText().toString()) == 0) {
                        aptitudeAdapter.setData(null);
                    } else {
                        int u = Integer.parseInt(noNum.getText().toString());
                        if (u <= issueNoListResponses.size()) {
                            aptitudeAdapter.setData(issueNoListResponses.subList(0, u));
                        } else {
                            aptitudeAdapter.setData(issueNoListResponses);
                        }
                    }
                    setResults();
                }
            }
        });

        multiple.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (multiple.getText().toString().equals("")) {
                    multipleNumber = 0;
                } else {
                    multipleNumber = Integer.parseInt(multiple.getText().toString());
                }

                setResults();
            }
        });

        listview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                removeSoftKeyboard(listview);
                return false;
            }
        });
    }

    private void setResults() {
        if(getArguments().getBoolean("isAdvanced")){
            if(aptitudeAdapter != null && aptitudeAdapter.getData() != null) {
                int v = 0;
                for(int i = 0; i < aptitudeAdapter.getData().size(); i++) {
                    IssueNoListResponse issueNoListResponse = aptitudeAdapter.getData().get(i);
                    if(intervalNumber == 0){
                        issueNoListResponse.setMultiple(multipleNumber);
                    } else {
                        issueNoListResponse.setMultiple(multipleNumber * (int)Math.pow(intervalMultipleNumber, v));
                        if((i + 1) % intervalNumber == 0) {
                            v++;
                        }
                    }
                }
            }
        } else {
            if(aptitudeAdapter != null && aptitudeAdapter.getData() != null) {
                for(IssueNoListResponse issueNoListResponse : aptitudeAdapter.getData()) {
                    issueNoListResponse.setMultiple(multipleNumber);
                }
            }
        }

        if(aptitudeAdapter != null) {
            if (aptitudeAdapter.getData() == null) {
                setResults(0, "0");
            } else {
                float num = 0;
                for (IssueNoListResponse issueNoListResponse : aptitudeAdapter.getData()) {
                    num += issueNoListResponse.getMultiple() * getArguments().getFloat("money");
                }

                setResults(aptitudeAdapter.getData().size(), Utils.saveTwoFormat(num));
            }
            if(listview.getAdapter() == null){
                View view = new View(getActivity());
                AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, Utils.dip2px(getActivity(), 70));
                view.setLayoutParams(layoutParams);
                listview.addFooterView(view);
                listview.setAdapter(aptitudeAdapter);
            } else {
                aptitudeAdapter.notifyDataSetChanged();
            }
        }
    }

    public void setResults2() {
        if (aptitudeAdapter.getData() != null) {
            float sum = 0;
            for (IssueNoListResponse issueNoListResponse : aptitudeAdapter.getData()) {
                sum += getArguments().getFloat("money") * issueNoListResponse.getMultiple();
            }

            aptitudeAdapter.notifyDataSetChanged();

            setResults(aptitudeAdapter.getData().size(), Utils.saveTwoFormat(sum));
        }
    }

    private void getList() {
        RetrofitBase.getRetrofit().create(IssueNoListRequest.class).getResult(getArguments().getString("code"))
                .compose(RxHelper.<ArrayList<IssueNoListResponse>>handleResult())
                .subscribe(new RxSubscribe<ArrayList<IssueNoListResponse>>(getActivity()) {
                    @Override
                    protected void _onNext(ArrayList<IssueNoListResponse> issueNoListRespsonses) {
                        issueNoListResponses = issueNoListRespsonses;

                        if(aptitudeAdapter == null) {
                            aptitudeAdapter = new AptitudeAdapter(AptitudeFragment.this);
                        }
                        if (issueNoListResponses.size() >= 10) {//最多保留10期
                            aptitudeAdapter.setData(issueNoListResponses.subList(0, 10));
                        } else {
                            aptitudeAdapter.setData(issueNoListResponses);
                        }

                        setResults();
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    @OnClick(R.id.confirm)
    public void onViewClicked() {
        if(aptitudeAdapter != null && aptitudeAdapter.getData() != null) {
            if ((getArguments().getLong("no") + 1) == aptitudeAdapter.getData().get(0).getIssue_no()) {
                addBet();
            } else {
                Dialog dialog = new AlertDialog.Builder(getContext())
                        .setMessage("期次已变化，当前是" + (aptitudeAdapter.getData().get(0).getIssue_no() -1) + "期，是否继续投注？")//设置提示内容
                        //确定按钮
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                addBet();
                            }
                        })
                        //取消按钮
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create();//创建对话框
                dialog.show();//显示对话框
            }
        }
    }

    private void addBet(){
        //sendAnalyticMsg("lottery_" + BetListActivity.ANALYTIC_VERSION + "_betrecord_autoadd_betbtn");

        JSONArray jsonArray = new JSONArray();
        for(BetListActivity.Result result : results.getList()){
            JSONObject jsonObject = new JSONObject();
            try {
//                jsonObject.put("period_no", aptitudeAdapter.getData().get(0).getIssue_no() - 1);//当前期号比列表里的第一行的期号少1
                jsonObject.put("rule_id", result.rule_id);

                String re;
                if (getArguments().getString("code").equals("gd11x5") || getArguments().getString("code").equals("bjpk10")) {
                    re = result.result
                        .replaceAll("01", "1")
                        .replaceAll("02", "2")
                        .replaceAll("03", "3")
                        .replaceAll("04", "4")
                        .replaceAll("05", "5")
                        .replaceAll("06", "6")
                        .replaceAll("07", "7")
                        .replaceAll("08", "8")
                        .replaceAll("09", "9");
                } else {
                    re = result.result;
                }

                jsonObject.put("pick_number", re);
                jsonObject.put("position", result.checkbox_string);
                jsonObject.put("amount_per_note", result.amount_per_note);
                jsonObject.put("note_count", result.num);
                jsonObject.put("odds", result.odds);
                jsonObject.put("rakeback", result.rakeback);
                jsonObject.put("is_follow", 1);
                jsonObject.put("is_win_stop", aptitudeLotteryActivity.is_win_stop ? 1 : 0);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        JSONArray jsonArray1 = new JSONArray();//追号的数据
        for(IssueNoListResponse issueNoListResponse : aptitudeAdapter.getData()){
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("period_no", issueNoListResponse.getIssue_no());
                jsonObject.put("multiple", issueNoListResponse.getMultiple());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray1.put(jsonObject);
        }

        RetrofitBase.getRetrofit().create(CreateOrderRequest.class).getResult(jsonArray, UserInfo.getToken(), jsonArray1)
                .compose(RxHelper.<CreateOrderResponse>handleResult())
                .subscribe(new RxSubscribe<CreateOrderResponse>(getActivity()) {
                    @Override
                    protected void _onNext(CreateOrderResponse createOrderResponse) {
                        Utils.showToast(createOrderResponse.getMsg());

                        if(results != null){
                            results.clear();
                        }

                        AddBetSuccess addBetSuccess = new AddBetSuccess();
                        addBetSuccess.setAfter_amount(createOrderResponse.getAfter_amount());
                        EventBus.getDefault().post(addBetSuccess);

                        getActivity().finish();
                    }

                    @Override
                    public boolean showDialog() {
                        return true;
                    }
                });
    }
}